package com.shoufeng.server;

import com.shoufeng.service.MessageServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import java.io.File;
import java.io.IOException;

public class MessageServer {

  private String userDir = System.getProperty("user.dir");

  private Server server;

  private void start() throws IOException {
    this.server = ServerBuilder.forPort(8080).addService(new MessageServiceImpl())
        .useTransportSecurity(new File("ssl/server.crt"), new File("ssl/server.pem"))
        .build().start();
    System.out.println("server start!");
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
      System.out.println("关闭jvm");
      MessageServer.this.stop();
    }));
//    System.out.println("执行到这里");
  }

  private void stop() {
    if (null != this.server) {
      this.server.shutdown();
    }
  }

  private void awaitTermination() throws InterruptedException {
    if (null != this.server) {
//      this.server.awaitTermination(3000, TimeUnit.MILLISECONDS);
      this.server.awaitTermination();
    }
  }

  public static void main(String[] args) throws InterruptedException, IOException {
    MessageServer greeterGrpcServer = new MessageServer();
    greeterGrpcServer.start();
    greeterGrpcServer.awaitTermination();
  }

  public static void main1(String[] args) {
    System.out.println(System.getProperty("user.dir"));
  }
}
